import React, { useEffect, useRef, useState } from 'react';
import { Input, Slider } from 'antd';
import { FormItem, Form, $Formutil } from 'react-antd-formutil';
import { eventBus } from '../../utils';
import { PickerItemData } from '../Picker/config';
import './style.css';

function PropsEditor() {
    const formutilRef = useRef<$Formutil>();
    const [data, setData] = useState<PickerItemData>();

    useEffect(() => {
        eventBus.on('edit:item', data => {
            setData(undefined);
            setTimeout(() => setData({ ...data }));
        });
    }, []);

    return (
        <div className="panel-props-editor">
            {data && (
                <Form
                    $defaultValues={data}
                    $onFormChange={formutil => {
                        if (formutil.$dirty) {
                            eventBus.emit('update:item', { ...data, ...formutil.$params }, data.key);
                        }
                    }}>
                    {formutil => {
                        formutilRef.current = formutil;

                        return renderItems(data);
                    }}
                </Form>
            )}
        </div>
    );
}

export default PropsEditor;

function renderItems(data: any, prefix?: string) {
    return (
        data &&
        Object.keys(data).map(k => {
            const item = (data as any)[k];

            if (['key', 'componentName', 'type'].includes(k)) {
                return null;
            }

            if (typeof item === 'object') {
                return (
                    <div key={k}>
                        <h3>{k}</h3>
                        {Object.keys(item).length === 0 ? <p style={{ color: 'gray' }}>暂无可编辑属性</p> : renderItems(item, k)}
                    </div>
                );
            }

            let control;

            if (k === 'span') {
                control = <Slider min={1} max={24} />;
            } else {
                control = <Input />;
            }

            return (
                <FormItem key={k} name={prefix ? `${prefix}.${k}` : k} itemProps={{ label: k }}>
                    {control}
                </FormItem>
            );
        })
    );
}
